﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BlogSolution
{
    public class FilterMemoryCacheAttribute : Attribute, IResourceFilter
    {
        private readonly IMemoryCache _memoryCache;

        //ICO 依赖注入，用之前 需要在服务文件中进行注入服务
        public FilterMemoryCacheAttribute(IMemoryCache memoryCache)
        {
            this._memoryCache = memoryCache;
        }

        //控制器执行完要走的方法
        public void OnResourceExecuted(ResourceExecutedContext context)
        {
            string key = string.Format($"{context.HttpContext.Request.Path}{context.HttpContext.Request.QueryString}");
            _memoryCache.Set(key, context.Result, TimeSpan.FromMinutes(10));
        }



        //刚进入控制器要走的方法   如果对context.Result 进行赋值 则原来控制器内的方法不再执行
        public void OnResourceExecuting(ResourceExecutingContext context)
        {
            string key = string.Format($"{context.HttpContext.Request.Path}{context.HttpContext.Request.QueryString}");
            if (_memoryCache.TryGetValue(key,out object val))
            {
                IActionResult result = val as IActionResult;
                if (result != null)
                {
                    context.Result = result;
                }
            }
        }
    }
}
